package com.aote.entity.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.w3c.dom.Element;

import com.aote.mvc.event.Action;
import com.browsesoft.SequenceFind;
import com.browsesoft.dbtools.BSConnection;
import com.browsesoft.user.User;

public class LoginAction extends Action {

	public void performAction(Element config, HttpServletRequest request,
			Map attrs) {
		String sealSessionID = insertToAip_sessionTable(request, (User) attrs
				.get("user"));
		request.getSession().setAttribute("sealsessionid", sealSessionID);
	}

	/**
	 * 向aip_session表插入记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private String insertToAip_sessionTable(HttpServletRequest request,
			User user) {
		try {
			// 生成sessionID,得到userid,的大开始时间
			String sessionID = Integer.toString(SequenceFind.getID());
			String userID = user.getID();
			String time = String.valueOf(System.currentTimeMillis()).substring(
					1, 10);
			// 执行sql
			BSConnection conn = new BSConnection();
			Connection c = conn.getConnection();
			Statement state = c.createStatement();
			// 如果已存再改用户记录
			String sqlQuery = "select * from aip_session where MY_USER_ID='"
					+ userID + "'";
			System.out.println(sqlQuery);
			ResultSet rs = state.executeQuery(sqlQuery);
			// 如果有记录
			if (rs.next()) {
				String sql = "update aip_session set SESSION_ID='" + sessionID
						+ "',START_TIME=" + time + " where MY_USER_ID= '"
						+ userID + "'";
				System.out.println(sql);
				state.executeUpdate(sql);
			}
			// 如果吴记录修改
			else {
				String sql = "insert into aip_session values('" + sessionID
						+ "','" + userID + "'," + 0 + "," + time + "," + 0
						+ ")";
				System.out.println(sql);
				state.execute(sql);
			}
			state.close();
			c.close();
			return sessionID;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}
